# -*- coding: utf-8 -*-

import logging
from odoo import http
from odoo.http import request
from odoo.addons.web.controllers.main import Home

_logger = logging.getLogger(__name__)


class DeviceAPIMiddleware:
    """设备API中间件 - 处理API路由和CORS"""
    
    def __init__(self, app):
        self.app = app
    
    def __call__(self, environ, start_response):
        """处理HTTP请求"""
        path_info = environ.get('PATH_INFO', '')
        
        # 如果是API请求，添加CORS头
        if path_info.startswith('/api/'):
            def custom_start_response(status, headers, exc_info=None):
                # 添加CORS头
                cors_headers = [
                    ('Access-Control-Allow-Origin', '*'),
                    ('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS'),
                    ('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Requested-With'),
                    ('Access-Control-Max-Age', '86400'),
                ]
                
                # 检查是否已存在CORS头，避免重复
                existing_headers = {h[0].lower() for h in headers}
                for header, value in cors_headers:
                    if header.lower() not in existing_headers:
                        headers.append((header, value))
                
                return start_response(status, headers, exc_info)
            
            # 处理OPTIONS预检请求
            if environ.get('REQUEST_METHOD') == 'OPTIONS':
                response_headers = [
                    ('Content-Type', 'text/plain'),
                    ('Access-Control-Allow-Origin', '*'),
                    ('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS'),
                    ('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Requested-With'),
                    ('Access-Control-Max-Age', '86400'),
                ]
                custom_start_response('200 OK', response_headers)
                return [b'']
            
            return self.app(environ, custom_start_response)
        
        return self.app(environ, start_response)


class DeviceHome(Home):
    """扩展Home控制器，防止API重定向"""
    
    @http.route('/api/<path:path>', type='http', auth='none', csrf=False, methods=['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'])
    def api_catchall(self, path=None, **kw):
        """捕获所有API请求，防止重定向到login页面"""
        # 如果是API请求但没有匹配的路由，返回404而不是重定向
        return request.not_found()
    
    @http.route('/', type='http', auth='none')
    def index(self, s_action=None, db=None, **kw):
        """重写首页，API请求不重定向"""
        # 检查是否是API请求
        if request.httprequest.path.startswith('/api/'):
            return request.not_found()
        
        # 对于普通web请求，使用原始逻辑
        return super().index(s_action=s_action, db=db, **kw)
    
    @http.route('/web/login', type='http', auth='none')
    def web_login(self, redirect=None, **kw):
        """重写登录页面，API请求返回JSON错误"""
        # 检查是否是API请求（通过Accept头或路径判断）
        accept = request.httprequest.headers.get('Accept', '')
        path = request.httprequest.path
        
        if (path.startswith('/api/') or 
            'application/json' in accept or 
            request.httprequest.is_xhr):
            # API请求返回JSON错误
            return request.make_response(
                '{"code": 401, "msg": "未登录或登录已过期", "data": null}',
                headers=[('Content-Type', 'application/json')]
            )
        
        # 普通web请求使用原始登录逻辑
        return super().web_login(redirect=redirect, **kw)
